package com.miguo.db;

import android.content.Context;

import com.miguo.app.AppContext;
import com.miguo.bean.ConfigBean;

import java.util.List;

import de.greenrobot.dao.query.QueryBuilder;

/**
 * File Names: ConfigDB
 * Describe:
 * User: LinXiaoZhi(87100854@qq.com)
 * Date: 2015-11-05
 * Time: 00:48
 */
public class ConfigDB {

    private static Context mContext;
    private static ConfigDB instance;

    private ConfigDao configDao;

    private ConfigDB() {
    }

    public static ConfigDB getInstance(Context context) {
        if (instance == null) {
            instance = new ConfigDB();
            if (mContext == null) {
                mContext = context;
            }

            // 数据库对象
            DaoSession daoSession = AppContext.getDaoSession(mContext, false);
            instance.configDao = daoSession.getConfigDao();
        }
        return instance;
    }

    public static ConfigDB getInstance(Context context, boolean ClearSession) {
        if (instance == null) {
            instance = new ConfigDB();
            if (mContext == null) {
                mContext = context;
            }

            // 数据库对象
            DaoSession daoSession = AppContext.getDaoSession(mContext, ClearSession);
            instance.configDao = daoSession.getConfigDao();
        }
        return instance;
    }

    /**
     * 查询
     */

    public List<ConfigBean> loadAll() {
        return configDao.loadAll();
    }

    /**
     * insert or update note
     *
     * @param goods
     * @return insert or update note id
     */
    public long save(ConfigBean goods) {
        return configDao.insertOrReplace(goods);
    }

    /**
     * insert or update noteList use transaction
     *
     * @param list
     */
    public void saveList(final List<ConfigBean> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        configDao.getSession().runInTx(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < list.size(); i++) {
                    ConfigBean note = list.get(i);
                    configDao.insertOrReplace(note);
                }
            }
        });
    }

    /**
     * 通过id查找其类型id
     */
    public String findValue(String name) {
        QueryBuilder<ConfigBean> qb = configDao.queryBuilder();
        qb.where(ConfigDao.Properties.Name.eq(name));
        if (qb.list().size() > 0) {
            return qb.list().get(0).getData();
        } else {
            return null;
        }
    }

    /**
     * delete all
     */
    public void deleteAll() {
        configDao.deleteAll();
    }
}
